0
0
NginxHow-ToBeginner · 3 min read

How to Use ^~ in Location Blocks in Nginx

In Nginx, the ^~ modifier in a location block tells Nginx to use this prefix match immediately and skip checking regular expressions. It is useful when you want to prioritize a specific path prefix without regex interference.
📐

Syntax

The ^~ modifier is used in a location block like this:

  • location ^~ /prefix/ { ... }

Here, ^~ means: if the request URI starts with /prefix/, use this block immediately without testing regex locations.

nginx
location ^~ /images/ {
    # configuration for /images/ prefix
}
💻

Example

This example shows how ^~ prioritizes a prefix match over regex locations:

nginx
server {
    listen 80;

    location ^~ /images/ {
        root /var/www/static;
    }

    location ~* \.(jpg|jpeg|png)$ {
        root /var/www/media;
    }

    location / {
        root /var/www/html;
    }
}
Output
Request to /images/logo.png serves file from /var/www/static/images/logo.png Request to /photos/pic.jpg serves file from /var/www/media/photos/pic.jpg Request to /index.html serves file from /var/www/html/index.html
⚠️

Common Pitfalls

Common mistakes when using ^~ include:

  • Expecting regex locations to be checked after a ^~ prefix match; they are skipped.
  • Using ^~ without a clear prefix, which can cause unexpected routing.
  • Confusing ^~ with exact match = or regex ~ modifiers.
nginx
location ^~ /images/ {
    # This block will always be used for URIs starting with /images/
}

location ~* \.(jpg|jpeg|png)$ {
    # This regex block will NOT be used for URIs starting with /images/
}
📊

Quick Reference

ModifierMeaningBehavior
Prefix matchUsed if no regex matches and no ^~ match
^~Prefix match with priorityStops regex checks if prefix matches
~Case-sensitive regexTested after prefix matches unless ^~ matched
~*Case-insensitive regexTested after prefix matches unless ^~ matched
=Exact matchHighest priority, stops all other checks

Key Takeaways

Use ^~ to prioritize prefix matches and skip regex location checks.
Requests matching a ^~ location block will not be tested against regex locations.
Do not confuse ^~ with exact match = or regex ~ modifiers.
Place ^~ locations before regex locations in your config for clarity.
Use ^~ when you want fast prefix matching without regex overhead.